<template>
  <div style="min-width: 300px;width: 100%;">
    <el-form label-width="80px" label-position="left">
      <el-form-item v-if="device.array" :label="$t('All')">
        <el-button-group>
          <el-button v-on:click="handleAll(true)" class="light-button"><i
              class="el-icon-switch-button success" />{{ $t('On') }}
          </el-button>
          <el-button v-on:click="handleAll(false)" class="light-button"><i
              class="el-icon-switch-button" />{{ $t('Off') }}
          </el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
    <template v-if="value.array">
      <el-row v-for="(item,index) in value.array" :key="'light_'+index">
        <light-item :value="item" />
      </el-row>
    </template>
    <div v-else :label="lightName(device)" style="display: flex;justify-content: center;margin-top: 20px;">
      <light-item :value="device" />
    </div>
  </div>
</template>
<script>
  import BaseController from './BaseController'
  import LightItem from '@/views/device/components/controller/LightItem.vue'
  export default {
    components: {
      LightItem
    },
    name: 'LampController',
    mixins: [BaseController, LightItem],
    data() {
      return {}
    },
    methods: {
      lightName(light) {
        if (!light.name || light.name.split('|').length < 4) {
          return this.$t('Light')
        }
        return light.name.split('|')[3]
      },
      handleChange(device, key, state) {
        var code = device.code
        var command = null
        var content = state ? 'ON' : 'OFF'
        if (code.indexOf("LIGHT_RELAY3_") >= 0) {
          command = "power" + key;
        } else if (code.indexOf("485_RELAY3_") >= 0) {
          command = "" + key;
          content = state ? "1" : "0"
        } else if (code.indexOf("BleGate_") >= 0) {
          command = 'control'
          var message = {}
          message['Light' + key] = content
          if (key === 0) {
            message = {
              "Light1": content,
              "Light2": content,
              "Light3": content
            }
          }
          const data = {
            "PackageType": 0,
            "DeviceControl": {
              "DevMac": code.split("@").pop(),
              "Message": message
            }
          }
          content = JSON.stringify(data)
        }
        this.doCommand(code, command, content);
      },
      handleAll(state) {
        const list = this.device.array
        for (var i = 0; i < list.length; i++) {
          setTimeout(this.handleChange, 1000 * i, list[i], 0, state)
        }
      }
    }
  }

</script>
<style scoped>
  .el-form-item {
    margin-bottom: 0px !important;
  }

  .light-button {
    width: 100px;
  }

</style>
